<template>
  <div class="concurrent">
    <h2>concurrent</h2>
    <br />
    <label for="total">
      总请求数:
      <input id="total" type="number" v-model="total" placeholder="总请求数" />个
    </label>
    <br />
    <label for="max">
      最大并发数:
      <input id="max" type="number" v-model="max" placeholder="最大并发数" />个
    </label>
    <br />
    <label for="delay">
      响应延时:
      <input id="delay" type="number" v-model="delay" placeholder="响应延时" />ms
    </label>
    <hr />
    <el-button @click="sendReqs">send request</el-button>
    <hr />
    <h3>Response:</h3>
    <ul class="xw-ul">
      <li v-for="item in resList" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref } from "vue";

// 请求数
const total = ref(10);
// 最大并发数，不超过6
const max = ref(2);
// 请求响应延时
const delay = ref(500);
// 请求池
let pool = [];
// const addReqs = () => {
//   for (let i = 0; i < total.value; i++) {
//     const url = "/api/test/" + i;
//     pool.push(() => {
//       return axios.get("/api/test/" + i).then((res) => {
//         console.log(url + " success");
//       });
//     });
//   }
//   console.log(pool);
// };
const doQueue = (maxNum = max.value) => {
  pool = [];
  // 最大并发数
  // 计数:当前请求数
  let current = 0;
  // 处理并发请求
  const doReq = () => {
    if (current < maxNum && pool.length > 0) {
      current++;
      console.log(pool);
      const curPromise = pool.shift();
      console.log(curPromise);

      curPromise()
        .then((res) => {
          console.log("=======执行成功", res);
        })
        .catch((e) => {
          console.log("======执行出错", e);
        })
        .finally(() => {
          console.log("=====执行完成");
          current--;
          doReq();
        });
    }
  };

  const addReq = (promiseFun) => {
    pool.push(promiseFun);
    doReq();
  };
  return addReq;
};

const resList = ref([]);
const sendReqs = () => {
  const addFun = doQueue();
  resList.value = [];
  for (let i = 0; i < total.value; i++) {
    const url = `http://localhost:3333/api/delay?delay=${delay.value}`;
    addFun(() => {
      return axios.get(url).then(() => {
        console.log(url + ` ${i} success`);
        resList.value = [...resList.value, url + ` 第${i}个请求 success`];
      });
    });
  }
};
</script>

<style lang="scss" scoped></style>
